import { Component, OnInit, AfterViewInit, Input} from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { ExpressionService } from '@core/services/expression/ExpressionService';

@Component({
  selector: 'apes-base-dialog-transfer',
  templateUrl: './apes-dialog-transfer.component.html',
})
export class ApesDialogTransferComponent implements OnInit, AfterViewInit {
  @Input() resultData: any[] = []; // 结果
  @Input() items : any[];
  @Input() api: string;
  @Input() domain: any;
  @Input() apiParams: any; // api默认条件
  @Input() valueFormatter: any;  // 显示格式
  @Input() value : any[];
  
  list: any[] = []; // 所有选项

  constructor(private apiService: ApiService,protected expressionService: ExpressionService,) {

  }

  ngOnInit() {
    this.getData();
  }

  getData() {
    if(this.api && !this.items) {
      let sendData = {size: 100, page: 0};
      if (this.domain) {
        sendData['domain'] = this.domain;
      }  
      if(this.apiParams) {
        sendData = {...sendData, ...this.apiParams}
      }
      this.apiService.post(this.api, {'body': JSON.stringify(sendData)}).subscribe(
        (body) => {
            if(body) {
                this.items = body.content;
                this.Init();
            }
       });
    }
  }

  ngAfterViewInit() {
     this.Init();
  }

  Init() {
    if(!this.items) return;
    let newItems = [];
    this.items.forEach(
      (value, index) => {
         newItems.push({
           key: value.id,
           title: this.formatter(value,this.getValueFormatter()),
           direction: ''          
         });
      }
    )
    if(this.value) {   
       this.value.forEach(
          (value, index) => {
             newItems.filter((item) => item.key === value.id).forEach(
               // tslint:disable-next-line:no-shadowed-variable
               (value, index) => {
                   value.direction = 'right';                 
               }
             )
          }
       );
       this.resultData = [...this.value];
    }
    this.list = newItems;
  }

  getValueFormatter(): string {
    return this.valueFormatter || 'value.name';
  }

  formatter(value: any, expression: string) {
    return this.expressionService.evaluate(expression, {
      value: value
    });
  }

  select(ret: any) {
    
  }

  change(ret: any) {
    if(ret['to'] === 'right') {
        let result = [];
        ret['list'].forEach(
          (value, index) => {
            result = [...this.items.filter(item => item.id === value.key),...result];
          }
        )
        this.resultData = [...this.resultData,...result];
    } else {       
       for (const list of ret['list']) {
         this.resultData.splice( this.resultData.findIndex(item => item.id === list['key']), 1);
       }
    }
  }

  
}
